package com.test.map;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.widget.ListPopupWindow;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.test.map.HTTP.OKHttp;
import com.test.map.sign.BaseActivity;
import com.test.map.sign.DateBaseHelper;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.FormBody;

public class MainActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {
    private SharedPreferences pref;//利用sharePREfreences来保存数据
    private SharedPreferences.Editor editor;//用来保存密码的
    private DateBaseHelper dphelp;
    private ListPopupWindow listPopupWindow;
    private EditText accountEdit;
    private EditText passwordEdit;
    private Button login;
    private Button sign;
    private CheckBox rember;
    private String list[];
    private CheckBox[] checkBoxes = new CheckBox[2];
    public int type=0;
    String s="";
    public OKHttp okHttp =  new OKHttp();
    @Override


    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        dphelp=new DateBaseHelper(this,"Users.db",null,1);//数据库的初始化
        rember=(CheckBox)findViewById(R.id.rember_1) ;//这个是复选框，用来选择是否选中密码的
        login=(Button)findViewById(R.id.login);
        sign=(Button)findViewById(R.id.Login_sign);//初始化
        //list.add("li");

        listPopupWindow=new ListPopupWindow(MainActivity.this);
        accountEdit=(EditText)findViewById(R.id.account) ;
        passwordEdit=(EditText)findViewById(R.id.password) ;
        pref= PreferenceManager.getDefaultSharedPreferences(this);
        Boolean isrember=pref.getBoolean("rember_pass",false);//初始设置记住密码为false
        DateBaseHelper database=new DateBaseHelper(this,"Users.db",null,1);
        if(isrember){
            int username=pref.getInt("username",0)-1;
            String id=pref.getString("account"+username,"");
            String pass=pref.getString("password"+username,"");
            accountEdit.setText(id);
            passwordEdit.setText(pass);//把保存的账号和密码读取出来
            rember.setChecked(true);
        }

        sign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//点击注册跳到注册的页面
                Intent intent=new Intent(MainActivity.this,Sign.class);
                startActivity(intent);
            }
        });

        login.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                accountEdit=(EditText)findViewById(R.id.account);//与相应的文本框对应起来
                passwordEdit=(EditText)findViewById(R.id.password);
                String userName=accountEdit.getText().toString();//获取文本框的数据
                String passWord=passwordEdit.getText().toString();
                if (login(userName,passWord)) {
                    final FormBody body = new FormBody.Builder()
                            .add("account",userName)
                            .add("password",passWord)
                            .build();

                    Toast.makeText(MainActivity.this, "登陆成功，欢迎来到新的世界", Toast.LENGTH_SHORT).show();//成功了弹出登陆成功
                    editor=pref.edit();
                    if(rember.isChecked()){//复选框是否被选中
                        int username=pref.getInt("username",0);
                        editor.putBoolean("rember_pass",true);//把记住密码设置为true
                        editor.putString("account"+username,userName);
                        editor.putString("password"+username,passWord);//把密码和账号分别保存到account和password里面
                        editor.putInt("username",username+1);
                    }
                    else{
                        editor.clear();//清空editor保存的东西
                    }
                    editor.apply();//启用editoy
                    String data=userName;
                    if (type==0){

                        new Thread(new Runnable(){
                            @Override
                            public void run() {
                                try {
                                    okHttp.post("http://47.105.179.182:5000/signin/user",body );
                                    Thread.sleep(2*1000);
                                    s=okHttp.s;
                                    JSONObject jsonObject=new JSONObject(s);
                                    App app=(App) getApplication();
                                    app.setUid(jsonObject.getString("id"));
                                    Log.d("1",app.Uid);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                        }).start();

                        Intent intent=new Intent(MainActivity.this,MapActivity.class);
                        startActivity(intent);
                    }
                    else {
                        new Thread(new Runnable(){
                            @Override
                            public void run() {
                                try {
                                    okHttp.post("http://47.105.179.182:5000/signin/driver",body );
                                    Thread.sleep(3*1000);
                                    s=okHttp.s;
                                    JSONObject jsonObject=new JSONObject(s);
                                    App app=(App) getApplication();
                                    app.setUid(jsonObject.getString("id"));
                                    Log.d("1",app.Uid);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                        }).start();


                        Intent intent=new Intent(MainActivity.this,DriverMap.class);
                        startActivity(intent);
                    }
                    //intent.putExtra("ex",data);//把当前登陆成功的账号的数据传递给下一个活动，用来显示是谁登陆成功了

                }

                else {
                    Toast.makeText(MainActivity.this, "登陆失败", Toast.LENGTH_SHORT).show();//失败，弹出登陆失败
                }
            }});
        accountEdit.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {//设置监听事件
                final int DRAWABLE_LEFT = 0;
                final int DRAWABLE_TOP = 1;
                final int DRAWABLE_RIGHT = 2;
                final int DRAWABLE_BOTTOM = 3;

                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (event.getX() >= (accountEdit.getWidth() - accountEdit
                            .getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                        //当点击了箭头位置的时候回调用下面的函数，显示出下拉框
                        accountEdit.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.ic_arrow_drop_down_white_24dp), null);
                        showListPopulWindow();
                        return true;
                    }
                }
                return false;
            }
        });

        checkBoxes[0] = (CheckBox) findViewById(R.id.guest1);
        checkBoxes[1] = (CheckBox) findViewById(R.id.driver1);
        checkBoxes[0].setOnCheckedChangeListener( this);
        checkBoxes[1].setOnCheckedChangeListener( this);



    }
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if(b) {
            for (int i = 0; i < checkBoxes.length; i++) {
                //不等于当前选中的就变成false
                if (checkBoxes[i].getText().toString().equals(compoundButton.getText().toString())) {
                    checkBoxes[i].setChecked(true);
                    type=i;
                } else {
                    checkBoxes[i].setChecked(false);
                }
            }
        }
    }
    public  void showListPopulWindow(){//用来显示下拉框
        final String acc[]=new String[pref.getInt("username",0)];//定义一个账号数组，长度为选择记住密码的登录成功的账号个数
        final String pas[]=new String[pref.getInt("username",0)];//定义一个密码数组，长度为选择记住密码的登录成功的账号个数
        for(int a=0;a<pref.getInt("username",0);a++){
            acc[a]=pref.getString("account"+a,"");//初始化账号数组，把已保存的账号放到数组里面去
            pas[a]=pref.getString("password"+a,"");//初始化密码数组，把已保存的密码放到数组里面去
        }

        listPopupWindow = new ListPopupWindow(MainActivity.this);
        listPopupWindow.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, acc));//把账号的数据显示到下拉列表里面去
        listPopupWindow.setAnchorView(accountEdit);
        listPopupWindow.setModal(true);

        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {//设置项点击监听

            @Override

            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                accountEdit.setText(acc[i]);//当选中下拉框的某一个选项的时候，把选择的选项内容展示在EditText上
                passwordEdit.setText(pas[i]);//将选中的账号的密码显示出来，显示在面板上，
                listPopupWindow.dismiss();//如果已经选择了，隐藏起来
            }
        });

        listPopupWindow.show();
    }

    public boolean login(String username, String password) {//验证此账号密码是否正确
        SQLiteDatabase db = dphelp.getWritableDatabase();
        String sql = "select * from userData where id=? and password=?";//将登录时填的账号和密码在数据库里面进行查询，如果存在该数据，则返回true，否则返回false
        Cursor cursor = db.rawQuery(sql, new String[] {username, password});
        if (cursor.moveToFirst()) {
            cursor.close();
            return true;
        }
        return false;
    }

}








